#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/cdev.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/mutex.h>
#include <linux/interrupt.h>
#include <linux/bug.h>			/* For BUG_ON.  */
#include <linux/cpu.h>
#include <linux/init.h> /* Needed for the macros */
#include <linux/kernel.h> /* Needed for pr_info() */
#include <linux/module.h> /* Needed by all modules */
#include <linux/delay.h>
#include <linux/smp.h>
#include <linux/kernel_stat.h>
#include <linux/sched.h>
#include <linux/percpu-defs.h>
#include <linux/wait.h>
#include <linux/gpio/driver.h>
#include <linux/atomic.h>
#include <linux/platform_device.h>
#include <linux/poll.h>
#include <linux/kfifo.h>


#define  TRUE(exp)   BUG_ON(!(exp))

//void* kmalloc(size_t size, int flags);

//sudo mknod /dev/mycdev001 c  403 0

/**
 * make
 * make scp
 *
 * test ok on tinkerboard.
 *
 * need to get major number from /proc/devices
 *
 * sudo mknod /dev/mydev1012 c 238 0
 *
 *
 *
 *

 sudo cat /proc/iomem

 ff720000-ff7200ff : /pinctrl/gpio0@ff720000
 ff730000-ff7300ff : /pinctrl/gpio1@ff730000
 ff780000-ff7800ff : /pinctrl/gpio2@ff780000
 ff788000-ff7880ff : /pinctrl/gpio3@ff788000
 ff790000-ff7900ff : /pinctrl/gpio4@ff790000



 RK3399 has 5 groups of GPIO banks: GPIO0~GPIO4, and each group is distinguished by numbers A0~A7, B0~B7, C0~C7, D0~D7.

 地址：
 GPIO0 ： FF72_0000
 GPIO1 ： FF73_0000
 GPIO2 ： FF78_0000
 GPIO3 ： FF78_8000
 GPIO4 ： FF79_0000


 Offset
 GPIO_SWPORTA_DR  : 0x0000
 GPIO_SWPORTA_DDR : 0x0004

 GPIO_1_A7

 Interrupts :
 46       gpio0_int
 47       gpio1_int
 48       gpio2_intr
 49       gpio3_intr
 50       gpio4_intr



 Whenever Port A is configured for interrupts, the data direction must be set to Input

 unsigned long probe_irq_on(void);

 int probe_irq_off(unsigned long);

 **/

//#define MY_MAJOR       499
#define GPIO_1_BASE  0xFF730000
#define  GPIO1_SWPORTA_DR GPIO_1_BASE
#define  GPIO1_SWPORTA_DDR  0xFF730004

#define  GPIO_INTEN   (GPIO_1_BASE + 0x0030)
#define  GPIO_PIN  39

#define LOCATION  7

//#define GPIO_1_A7  0x1

//#define  DIRECTION_OUT 255
//
//#define  LED1_ON    255

#define MY_MAX_MINORS  3
#define   DEVICE_NAME  "device name 500"

DEFINE_KFIFO(myfifo, char, 1024);

struct my_device_data {
	struct cdev cdev;
	char *content;
};

DECLARE_WAIT_QUEUE_HEAD(wq);

/**
 *  cat /sys/module/a2/parameters/name
 */

//module_param(name, charp, S_IRUGO);
static struct my_device_data devs[MY_MAX_MINORS];

static DEFINE_MUTEX(my_mutex_lock);

//static irqreturn_t key_handler(int irq, void *dev_id) {
//	pr_err("key_handler \n");
//	return IRQ_HANDLED;
//}



char *ff;
static int my_open(struct inode *inode, struct file *file) {
	struct my_device_data *p;
	pr_info("a3 my_open \n");
	p = container_of(inode->i_cdev, struct my_device_data, cdev);
	p->content = (char*) kmalloc(1024, GFP_KERNEL);
	memcpy(p->content,
			"The kmalloc allocation engine is a powerful tool and easily learned because of its similarity to malloc. "
					"The function is fast (unless it blocks) and doesn’t clear the memory it obtains; the allocated region still holds its previous content.[1] "
					"The allocated region is also contiguous in physical memory",
			1024);
	file->private_data = p;
	return 0;
}

//static unsigned char mem[100];

unsigned int num;

int flag = 0;

static ssize_t my_write(struct file *filp, const char __user *user_buffer,
		size_t size, loff_t *offset) {
	int ret;
//	size_t my_size = 100;
	unsigned int len = 0;
//	pr_info("a3 my_write\n");
	pr_info("write");
	ret=kfifo_from_user(&myfifo,user_buffer,size,&len);
	if(ret!=0){
		pr_err("kfifo_from_user error");
		return  0;
	}
	if (len <= 0)
		return 0;
////
//	/* read data from user buffer to my_data->buffer */
//	if (copy_from_user(mem + *offset, user_buffer, len))
//		return -EFAULT;
	*offset += len;
//	pr_info("r: %s", mem);
	return len;
}

static ssize_t my_read(struct file *filp, char __user *user_buffer, size_t count,
		loff_t *offset) {
	int ret;
	//	size_t my_size = 100;
		unsigned int len = 0;
	//	pr_info("a3 my_write\n");
		pr_info("read");
		ret=kfifo_to_user(&myfifo,user_buffer,count,&len);
		if (len <= 0)
				return 0;


//	struct my_device_data *device_data = filp->private_data;
//	int p = *offset;
//	char *data = device_data->content;
//	size_t datalen = strlen(data);
//	pr_info("my_read offset: %lld\n", *offset);
//	if (p > datalen) {
//		return 0;
//	}
//	if (count > datalen - p) {
//		count = datalen - p;
//	}
//	if (copy_to_user(buffer, data + *offset, count)) {
//		return -EFAULT;
//	}
	*offset += len;
	return len;
}

static atomic_t count = ATOMIC_INIT(0);

static DEFINE_PER_CPU(long, my_counter) = 0;

static int my_close(struct inode *inode, struct file *filp) {
	char *mychar2 = kmalloc(1024,GFP_KERNEL);
	int  number;
	int total = 0;
	int cpu;
	struct my_device_data *device_data = filp->private_data;
	pr_info("a3 my_close\n");
	for_each_possible_cpu(cpu)
	{
		int tmp = per_cpu(my_counter, cpu);
		pr_info("cpu: %d,has  %d\n", cpu, tmp);
		total += tmp;
	}
	pr_info("total access:  %d\n", total);
	kfree(device_data->content);

	number = kfifo_out_peek(&myfifo, mychar2, kfifo_size(&myfifo));
	mychar2[number]='\0';
	pr_info("myfifo content:  %s\n", mychar2);
	return 0;
}

static long my_ioctl(struct file *file, unsigned int cmd, unsigned long arg) {
	int z;
	int r;
//	pr_info("cpu number: %d\n",num_online_cpus());
//	pr_info("num_possible_cpus cpu number: %d\n",num_possible_cpus());
	switch (cmd) {
	case 10:
		pr_info("0 wait_event_interruptible\n");
		wait_event(wq, flag != 0);
		pr_info("0 wait_event_interruptible:  %d\n", r);
		pr_info("0 wait_event_interruptible 2 \n");
		flag = 0;
		break;
	case 11:
		flag = 1;
		pr_info("1 start to wake_up  0 now \n");
		wake_up(&wq);
		break;
	case 0: {
//		mdelay(1000);
		this_cpu_inc(my_counter);
		z = this_cpu_read(my_counter);
//		this_cpu_write(my_counter,100);
		pr_info("this_cpu_read: %d\n", z);

//		this_cpu_add(my_counter,2);
//		int cpu = get_cpu(); /* prevent preemption/migration */
////		pr_info("my  cpu  == %d \n", cpu);
//		per_cpu(my_counter, cpu)++;
//		put_cpu();

//		get_cpu_var(my_counter)++;
//		put_cpu_var(my_counter);

		if (mutex_lock_interruptible(&my_mutex_lock))
			return -ERESTARTSYS;
		atomic_inc(&count);
//		count++;
//		pr_err("cmd 0 's arg is: %ld \n", arg);
//		pr_info("count == %d\n",	atomic_read(&count));
//		pr_info("count == %d, 0   \n",	atomic_read(&count));
//		pr_info("count == %d, 1   \n",	atomic_read(&count));
//		pr_info("count == %d, 2   \n",	atomic_read(&count));
//		pr_info("count == %d, 3   \n",	atomic_read(&count));
//		pr_info("count == %d, 4   \n",	atomic_read(&count));
		mutex_unlock(&my_mutex_lock);
		break;
	}
	case 1: {
		pr_err("cmd 1's arg is: %ld \n", arg);
		break;
	}
	default: {
		pr_err("cmd is: %d, arg is %ld \n", cmd, arg);
	}
	}
	return 0;
}

unsigned int my_poll(struct file *flip, struct poll_table_struct *table) {
	int mask = 0;
	pr_info("my_poll \n");
	mask |= POLLIN | POLLRDNORM;
	return mask;
}

static const struct file_operations my_fops = { .owner = THIS_MODULE, .open =
		my_open, .read = my_read, .write = my_write, .release = my_close,
		.unlocked_ioctl = my_ioctl, .poll = my_poll,

};

static dev_t mydev;


//char  mychar[] = "abcdef";

static __init int my_init(void) {
	char out;
	int ret;
	char *mychar2 = kmalloc(1024,GFP_KERNEL);
	int i;
	int err;
	int  number;


//	pr_info("111111111111111  %c\n",out);
//		unsigned int __iomem *direction = ioremap(GPIO1_SWPORTA_DDR, 4);
//		unsigned int a = readl(direction);
//		unsigned int __iomem *irq = ioremap(GPIO_INTEN, 4);
//
//	// set direction in
//		writel(readl(direction) & (~(1 << LOCATION)), direction);
//		//just check
//		a = readl(direction);
//		pr_err("direction: %d \n", a);

//pr_err("direction 1 or 0  ? : %d \n", (a & (1 << LOCATION)) >> LOCATION);
//
//// enable Interrupt
//writel(readl(irq) | (1 << LOCATION), irq);
//
//		pr_err("Interrupt 1 or 0  ? : %d \n",
//		(readl(irq) & (1 << LOCATION)) >> LOCATION);
//
//num = gpio_to_irq(GPIO_PIN);
//
//		pr_info("irq_num:%d\n", num);
//
//ret = request_irq(num, key_handler, IRQF_TRIGGER_LOW,
//					"key_interrupt", NULL);
//
//		if (ret < 0) {
//				pr_err("request_irq  failed \n");return ret;
//			}

	pr_info("a3 init_module\n");err = alloc_chrdev_region(&mydev, 0, MY_MAX_MINORS, DEVICE_NAME);
	if (err != 0) {
		return err;
	}

	for (i = 0; i < MY_MAX_MINORS; i++) {
		/* initialize devs[i] fields */
		cdev_init(&devs[i].cdev, &my_fops);
		cdev_add(&devs[i].cdev, MKDEV(MAJOR(mydev), i), 1);
	}

	kfifo_in(&myfifo, mychar,strlen(mychar));
	TRUE(!kfifo_is_empty(&myfifo));
	TRUE(kfifo_len(&myfifo)==5);
	TRUE(kfifo_avail(&myfifo)==1024-5);
	TRUE(!kfifo_is_full(&myfifo));

//	ret=kfifo_put(&myfifo, 'e');
//	if(ret==0){
//		pr_err("myfifo is full \n");}
//
////	BUG_ON(1==1);
//
//	kfifo_put(
//		&myfifo, 'n');
//	if(ret==0){
//			pr_err("myfifo is full \n");}
//	kfifo_put(&myfifo, 'd');
//	if(ret==0){
//			pr_err(
//		"myfifo is full \n");}

	number = kfifo_out(&myfifo, mychar2, kfifo_len(&myfifo));
	if(number<=0){
		pr_err(
		"kfifo_out  failed \n");}
	mychar2[number]='\0';
	pr_info("copied 2 number:  %d\n", number);
	pr_info(
		"kfifo_out: %s\n", mychar2);


	TRUE(!strcmp("12345",mychar2));

	ret=kfifo_put(&myfifo, 'e');
		if(ret==0){
			pr_err("myfifo is full \n");}

		ret= kfifo_get(&myfifo, &out);

		TRUE(out == 'e');

		if(ret==0)
					pr_err(
				"myfifo is empty\n");
		else
		pr_info("kfifo_get: %c", out);

return 0;
}

static void __exit my_exit(void) {
		int i;
		free_irq(num, NULL);
		pr_info("a3 cleanup_module\n");
		for (i = 0; i < MY_MAX_MINORS; i++) {
		/* release devs[i] fields */
		cdev_del(&devs[i].cdev);
		}
		unregister_chrdev_region(mydev, MY_MAX_MINORS);
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Andy");
MODULE_DESCRIPTION("andy one-key driver");
MODULE_ALIAS("one-key");
